﻿/*
 * Created by SharpDevelop.
 * User: Home
 * Date: 25/06/2008
 * Time: 12:02
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using csharp.rad.general;
using System.Windows.Forms;
using csharp.rad.sisponto.kernel;
using ComponentFactory.Krypton.Toolkit;

namespace csharp.rad.sisponto
{
	/// <summary>
	/// Description of frmExportarHorariosRelogioHenry.
	/// </summary>
	public partial class frmExportarHorariosRelogioHenry : KryptonForm
	{
		Database bdPostgres;
		Database bdInterbase;
		Database.Result result = new Database.Result();
		HorariosFunc horarios;
		String msgErro;
		
		public frmExportarHorariosRelogioHenry(Database bd)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			this.bdPostgres = bd;
			horarios = new HorariosFunc(bd);
		}
		
		private void preencheDataGrid()
		{
			int tam;

			tam = horarios.Items.Count;
			dgvHorarios.Rows.Clear();
			for (int i = 0; i < tam; i++)
			{
				String[] aux = { horarios.Items[i].id_secundario.ToString(),"true", horarios.Items[i].tipo };
				dgvHorarios.Rows.Add(aux);
			}
		}
		
		private int insertDescricao(String descricao)
		{
			String _sql =  " SELECT HE11_AT_COD "
				          +" FROM HE11 "
				          +" WHERE (HE11_ST_DESCHOR='"+descricao+"')";
			
			Object count = bdInterbase.ExecuteScalar(_sql,out result);
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}
			if( Convert.ToInt32(count) > 0)
				return Convert.ToInt32(count);
			
			_sql = "INSERT INTO HE11 (HE11_ST_DESCHOR) VALUES('"+descricao+"')";
			
			result = bdInterbase.ExecuteCommand(_sql, Database.doNotUseTransaction);
			
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}
			
		   _sql = "SELECT MAX(HE11_AT_COD) FROM HE11";
		   
		   Object id = bdInterbase.ExecuteScalar(_sql,out result);
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}
			
			return Convert.ToInt32(id);	
		}
		
		private int insertPeriodo(String diaSemana, String horaInicio, String horaFim)
		{
			String _sql = " SELECT HE15_AT_COD " +
				          " FROM HE15" +
				          " WHERE ( HE15_HR_HORINI = '"+horaInicio+"' )"+
				          " AND   ( HE15_HR_HOREND = '"+horaFim+"'    )"+
				          " AND   ( HE15_ST_DIAS   = '"+diaSemana+"'  )";
			
			Object count = bdInterbase.ExecuteScalar(_sql,out result);
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}
			if( Convert.ToInt32(count) > 0)
				return Convert.ToInt32(count);
			
			_sql = " INSERT INTO HE15 (HE15_HR_HORINI, HE15_HR_HOREND, HE15_ST_DIAS) " +
  	                   " VALUES('"+horaInicio+"','"+horaFim+"','"+diaSemana+"')";
			
			result = bdInterbase.ExecuteCommand(_sql, Database.doNotUseTransaction);
			
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}
			
		   _sql = "SELECT MAX(HE15_AT_COD) FROM HE15";
		   
		   Object id = bdInterbase.ExecuteScalar(_sql,out result);
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}
			
			return Convert.ToInt32(id);	
		}
		
		private int insertDescricaoPeriodo(String idDescricao, String idPeriodo)
		{
			String _sql = " SELECT COUNT(*) " +
				          " FROM HE09 " +
				          " WHERE HE09_NR_HORARIO = "+idDescricao +
				          " AND   HE09_NR_PERIODO = "+idPeriodo;
			
			Object count = bdInterbase.ExecuteScalar(_sql,out result);
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}
			if( Convert.ToInt32(count) > 0)
				return 1;
			
			_sql = " INSERT INTO HE09 (HE09_NR_HORARIO, HE09_NR_PERIODO) " +
  	                   " VALUES("+idDescricao+","+idPeriodo+")";
			
			result = bdInterbase.ExecuteCommand(_sql, Database.doNotUseTransaction);
			
			if( result.Status == Database.Status.Failed)
			{
				msgErro = result.ErrorMessage;
				return 0;
			}  	
			return 1;
		}
		
		
		private void BtnTestarConexaoClick(object sender, EventArgs e)
		{
			bdInterbase = new Database();
		
			bdInterbase.Protocol = "Firebird";
			bdInterbase.Host= txtHost.Text;
			bdInterbase.Name = txtBdName.Text;
			bdInterbase.User = txtUser.Text;
			bdInterbase.Password = txtPassword.Text;
			
			result = bdInterbase.Connect();
			if( result.Status == Database.Status.Failed )
			{
				KryptonMessageBox.Show("Erro: "+result.ErrorMessage);
				btnImportar.Enabled = false;
			}
			else
			{
				KryptonMessageBox.Show("Conexão efetuada com sucesso!");
				btnImportar.Enabled = true;
			}
		}
		
		private void FrmExportarHorariosRelogioHenryLoad(object sender, EventArgs e)
		{
			horarios.obter();
			
			preencheDataGrid();
		}
		
		private void exportaHorarios()
		{
			Int32 idDescricao, idPeriodo;
			HorariosFunc temp = new HorariosFunc(bdPostgres);
			HorarioFunc aux;
			TimeSpan     minus = new TimeSpan(0,Configuracao.tempo_tolerancia, 0);
			
			temp.obterTodos();
			
			bdInterbase.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
			for(int i = 0; i < dgvHorarios.Rows.Count; i++)
			{
				if( Convert.ToBoolean(dgvHorarios.Rows[i].Cells["exportar"].Value) )
				{
					idDescricao = insertDescricao(dgvHorarios.Rows[i].Cells["nome"].Value.ToString());
					
					//Erro
					if( idDescricao <= 0)
					{
						KryptonMessageBox.Show("Erro: "+this.msgErro);
						bdInterbase.RollBackTransaction();
						return;
					}
					//Busca o primeiro horário - 1 - segunda-feira
					temp.getHorarioFunc(Convert.ToInt32(dgvHorarios.Rows[i].Cells["id"].Value), 1);
					
					//Exporta os sete dias da semana
					for(int j= 1; j <= 7; j++)
					{
						aux = temp.Current();
						temp.Next();
						
						//Exportar a entrada, almoço, retorno e saida. Caso sejam diferente de 00:00:00
						if( !aux.entrada.ToString().Equals("00:00:00"))
						{
							idPeriodo = insertPeriodo(j.ToString(),aux.entrada.Subtract(minus).ToString(), aux.entrada.Add(minus).ToString());
							if( idPeriodo <= 0)
							{
								KryptonMessageBox.Show("Erro: "+this.msgErro);
								bdInterbase.RollBackTransaction();
								return;
							}							
							insertDescricaoPeriodo( idDescricao.ToString(), idPeriodo.ToString() );							
						}
						
						if( !aux.almoco.ToString().Equals("00:00:00"))
						{
							idPeriodo = insertPeriodo(j.ToString(),aux.almoco.Subtract(minus).ToString(), aux.almoco.Add(minus).ToString());
							if( idPeriodo <= 0)
							{
								KryptonMessageBox.Show("Erro: "+this.msgErro);
								bdInterbase.RollBackTransaction();
								return;
							}
							insertDescricaoPeriodo( idDescricao.ToString(), idPeriodo.ToString() );
						}
						
						if( !aux.retorno.ToString().Equals("00:00:00"))
						{
							idPeriodo = insertPeriodo(j.ToString(),aux.retorno.Subtract(minus).ToString(), aux.retorno.Add(minus).ToString());
							if( idPeriodo <= 0)
							{
								KryptonMessageBox.Show("Erro: "+this.msgErro);
								bdInterbase.RollBackTransaction();
								return;
							}
							insertDescricaoPeriodo( idDescricao.ToString(), idPeriodo.ToString() );
						}
						
						if( !aux.saida.ToString().Equals("00:00:00"))
						{
							idPeriodo = insertPeriodo(j.ToString(),aux.saida.Subtract(minus).ToString(), aux.saida.Add(minus).ToString());
							if( idPeriodo <= 0)
							{
								KryptonMessageBox.Show("Erro: "+this.msgErro);
								bdInterbase.RollBackTransaction();
								return;
							}
							insertDescricaoPeriodo( idDescricao.ToString(), idPeriodo.ToString() );
						}						
					}
				}
			}
			KryptonMessageBox.Show("Registros salvos com sucesso!");
			btnImportar.Enabled = false;
			bdInterbase.CommitTransaction();
		}
		
		private void BtnImportarClick(object sender, EventArgs e)
		{
			exportaHorarios();
		}
		
		private void BtnCancelarClick(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}
